package com.hsgene.order.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.hsgene.common.ClientType;
import com.hsgene.common.DeleteFlagType;
import com.hsgene.common.util.basic.JsonUtils;
import com.hsgene.common.util.basic.UUID32;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.date.SimpleDateUtils;
import com.hsgene.common.util.http.HttpConnectionManager;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.sign.PayDigestUtil;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.support.PeanutPagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.dict.dto.SysDictDto;
import com.hsgene.generator.constants.GeneratorEnum;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.order.condition.*;
import com.hsgene.order.constants.ExportType;
import com.hsgene.order.constants.PayType;
import com.hsgene.order.constants.PaymentStatus;
import com.hsgene.order.constants.ReportAduitStatus;
import com.hsgene.order.constants.v1.*;
import com.hsgene.order.domain.OrderPackage;
import com.hsgene.order.domain.OrderPackageDetail;
import com.hsgene.order.domain.PlatformOrderDto;
import com.hsgene.order.domain.v1.*;
import com.hsgene.order.dto.console.*;
import com.hsgene.order.dto.console.detail.*;
import com.hsgene.order.dto.message.OrderPostponeMessageDto;
import com.hsgene.order.dto.peanut.OrderCheckInfoDto;
import com.hsgene.order.dto.peanut.TestingOrderDto;
import com.hsgene.order.dto.v1.GeneticTestingExpressDeliveryDto;
import com.hsgene.order.dto.v1.OrderSettlementDto;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.order.persistence.*;
import com.hsgene.order.service.*;
import com.hsgene.order.service.api.*;
import com.hsgene.product.domain.GeneticTestingProductDetail;
import com.hsgene.product.dto.peanut.GeneticTestingProductDetailDto;
import com.hsgene.sample.dto.GeneticTestingSampleDto;
import com.hsgene.user.domain.DoctorDto;
import com.hsgene.user.domain.GeneticTestingOperationAccount;
import com.hsgene.user.domain.GeneticTestingUserAddress;
import com.hsgene.user.dto.address.AddressDetails;
import com.hsgene.user.dto.address.GeneticTestingUserAddressDetails;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: 江承良
 * @date: 2018/9/26 14:14
 */
@Service
public class ConsoleOrderServiceImpl implements ConsoleOrderService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ConsoleOrderServiceImpl.class);

    @Resource
    private ConsoleOrderRepository consoleOrderRepository;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderPackageMapper orderPackageMapper;
    @Resource
    private AgencyOrderRepository agencyOrderRepository;
    @Resource
    private OrderService orderService;
    @Resource
    private GeneratorService generatorService;
    @Resource
    private DictService dictService;
    @Resource
    private ConsignAddressService consignAddressService;
    @Resource
    private ExpressDeliveryRepository expressDeliveryRepository;
    @Resource
    private ApplyOrderService applyOrderService;
    @Resource
    private OrderPackageDetailMapper packageDetailMapper;
    @Resource
    private UserService userService;
    @Resource
    private SampleService sampleService;

    @Resource
    private UserAuthenticationService userAuthenticationService;

    @Resource
    private OrderPaymentRepository orderPaymentRepository;

    @Resource
    private ProductService productService;

    @Resource
    private OrderRefundRepository orderRefundRepository;

    @Resource
    private OrderPostponeService orderPostponeService;

    @Resource
    private OrderPackageRepository orderPackageRepository;

    @Resource
    private Producer producer;

    @Value("${genetic.testing.orders.receipt.limit}")
    private Integer ordersReceiptLimit;

    @Value("${mq.rocket.topic.genetic_testing_order}")
    private String orderTopic;

    @Value("${mq.rocket.tag.genetic_testing_order_auto_receipt}")
    private String autoReceiptTag;

    @Value("${mq.rocket.debug:false}")
    private Boolean mqRocketDebug;

    @Value("${peanut.qiniu.bucket}")
    private String peanutQiniuBucket;

    /**
     * 运营后台订单列表查询
     *
     * @param condition   检测套餐订单查询条件
     * @param limitHelper 分页条件
     * @param sortType    排序类型
     * @return
     */
    @Override
    public ApiResult<Pagination<ConsoleOrderDto>> queryConsoleOrders(
            QueryTestingProductOrderCondition condition, LimitHelper limitHelper, String sortType) {
        FieldChecker.checkEmpty(limitHelper, "分页条件");
        int count = 0;
        List<Integer> integers = consoleOrderRepository.consoleOrderCount(condition);
        if (integers != null && integers.size() > 0) {
            count = integers.size();
        }
        Pagination<ConsoleOrderDto> pagination = Pagination.newInstance(limitHelper, count);
        List<ConsoleOrderDto> consoleOrderDtos = new ArrayList<>();
        if (count > 0) {
            consoleOrderDtos = consoleOrderRepository.queryConsoleOrders(condition, limitHelper, sortType);
            if (consoleOrderDtos != null && consoleOrderDtos.size() > 0) {
                int rowNum = (limitHelper.getPage() - 1) * limitHelper.getSize();
                for (int i = 0; i < consoleOrderDtos.size(); i++) {
                    ConsoleOrderDto consoleOrderDto = consoleOrderDtos.get(i);
                    int status = consoleOrderDto.getStatus();
                    //状态转换
                    consoleOrderDto.setStatusDesc(OrderStatus.getEnum(status).getDesc());
                    //付费情况转换
                    if (StringUtils.isNotEmpty(consoleOrderDto.getChargeStatus())) {
                        consoleOrderDto.setChargeStatusDesc(OrderChargeStatus.getEnum(consoleOrderDto.getChargeStatus())
                                .getDesc());
                    } else {
                        consoleOrderDto.setChargeStatusDesc("未付款");
                    }
                    /*
                     * 是否显示寄送给用户按钮
                     */
                    if (consoleOrderDto.getStatus() == OrderStatus.WAIT_AGENCY_SEND.getCode()) {
                        //寄送给地服
                        int count1 = consoleOrderRepository.orderDeliveryCount(consoleOrderDto.getOrderId(), 1);
                        //*如果订单状态是待寄送至地服并且订单来源为商城订单，且用户选择的快递方式为快递寄送，且未寄送过的订单才显示寄送至用户按钮
                        if (ClientType.PC.getCode().equals(consoleOrderDto.getOrderOrigin())
                                || ClientType.APPLETS.getCode().equals(consoleOrderDto.getOrderOrigin())
                                || ClientType.APP.getCode().equals(consoleOrderDto.getOrderOrigin())) {
                            if (StringUtils.isNotEmpty(consoleOrderDto.getDeliveryMethod()) && consoleOrderDto
                                    .getDeliveryMethod().contains("快递") && count1 == 0) {
                                consoleOrderDto.setSendToCustomerBtn(1);
                            }
                        }
                    }
                    //查询报告待上传状态的套餐数量
                    int testingOrderStatusCount = consoleOrderRepository.testingOrderStatusCount(consoleOrderDto
                            .getOrderId());
                    //判断是否显示确认订单按钮（如果订单状态为报告待上传或者订单中存在报告待上传的套餐则显示确认报告按钮）
                    if (consoleOrderDto.getStatus() == OrderStatus.TESTING.getCode() || testingOrderStatusCount > 0) {
                        consoleOrderDto.setConfirmReportBtn(1);
                    }
                    //序号
                    consoleOrderDto.setNumber(rowNum + i + 1);
                    if (consoleOrderDto.getOrderOrigin() != null) {
                        consoleOrderDto.setFrom(ClientType.getEnum(consoleOrderDto.getOrderOrigin()).getIdentifier());
                    }
                }
            }
        }
        pagination.setResult(consoleOrderDtos);
        return ApiResult.succ(pagination);
    }

    @Override
    public ApiResult<Pagination<PostponeTestingOrderDto>> queryPostponeOrders(
            QueryTestingProductOrderCondition condition, OrderHelper orderHelper, LimitHelper limitHelper) {
        FieldChecker.checkEmpty(limitHelper, "分页查询条件");
        if (orderHelper != null) {
            orderHelper.validate(GeneticTestingOrderField.getInstance());
        }
        int orderCount = 0;
        List<Integer> peerCount = consoleOrderRepository.queryPostponeOrdersCount(condition);
        if (!CollectionUtils.isEmpty(peerCount)) {
            orderCount = peerCount.size();
        }
        Pagination<PostponeTestingOrderDto> pagination = Pagination.newInstance(limitHelper, orderCount);
        if (orderCount > 0 && limitHelper.getOffset() <= orderCount) {
            List<PostponeTestingOrderDto> postpones = consoleOrderRepository.queryPostponeOrders(condition, orderHelper, limitHelper);
            int number = limitHelper.getOffset();
            for (PostponeTestingOrderDto postpone : postpones) {
                postpone.setNumber(++number);
            }
            pagination.setResult(postpones);
        }

        return ApiResult.succ(pagination);
    }

    /**
     * @param signDto 标记信息
     * @param orderId 订单id
     * @param userId  用户id
     * @return void
     * @description 更新套餐订单标记状态
     * @author maodi
     * @createDate 2018/11/1 16:30
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public void updateOrderSign(SignDto signDto, String orderId, String userId) {
        consoleOrderRepository.updateOrderSign(signDto, orderId);
        Integer sign = signDto.getSignStatus();
        if (sign == 1) {
            consoleOrderRepository.updateOrderASign(signDto, orderId);
        }
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderId);
        orderOperationDetail.setOperatorId(userId);
        Integer status = orderRepository.getOrderStatusByOrderId(orderId);
        orderOperationDetail.setStatus(status);
        if (sign == 1) {
            orderOperationDetail.setDescription("标记订单");
        } else {
            orderOperationDetail.setDescription("确认标记订单");
        }
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
    }

    /**
     * @param orderId 订单id
     * @return com.hsgene.order.dto.console.SignDto
     * @description 根据订单id获取订单标记信息
     * @author maodi
     * @createDate 2019/1/17 11:05
     */
    @Override
    public SignDto getSignInfo(String orderId) {
        SignDto signDto = consoleOrderRepository.getSignInfo(orderId);
        String signProofs = signDto.getSignProofs();
        if (StringUtils.isNotBlank(signProofs)) {
            List<String> signProofList = QiniuCertificateUtil.getDownloadCertificateList(Arrays.asList(signDto
                    .getSignProofs().split(",")));
            signDto.setSignProofs(null);
            signDto.setSignProofList(signProofList);
        }
        return signDto;
    }

    /**
     * @param lock    锁定状态
     * @param orderId 订单id
     * @param userId  用户id
     * @return void
     * @description 更新套餐订单锁定状态
     * @author maodi
     * @createDate 2018/11/1 16:47
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public void updateOrderLock(Integer lock, String orderId, String userId) {
        consoleOrderRepository.updateOrderLock(lock, orderId);
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderId);
        orderOperationDetail.setOperatorId(userId);
        Integer status = orderRepository.getOrderStatusByOrderId(orderId);
        orderOperationDetail.setStatus(status);
        if (lock == 0) {
            orderOperationDetail.setDescription("取消锁定订单");
        } else {
            orderOperationDetail.setDescription("锁定订单");
        }
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
    }

    /**
     * 线下付款弹窗信息
     *
     * @param id 订单id
     * @return
     */
    @Override
    public ApiResult underLinePaymentInfo(String id) {
        TestingOrderDto testingOrderDto = orderRepository.underLinePaymentInfo(id);
        return new ApiResult(200, "success", "获取线下付款弹窗信息成功", testingOrderDto);
    }

    /**
     * 保存线下收款填写的信息并更改订单状态
     *
     * @param geneticTestingOrderAddtionB
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public ApiResult updateTestingOrder(GeneticTestingOrderAddtionB geneticTestingOrderAddtionB, String userId) {
        FieldChecker.checkEmpty(geneticTestingOrderAddtionB.getPaymentImageUrl(), "线下支付凭证");
        FieldChecker.checkMinMaxSize(Lists.newArrayList(geneticTestingOrderAddtionB.getPaymentImageUrl().split(",")),
                1, 9, "线下支付凭证图片", "张数");
        //判断订单是否符合线下收款条件
        GeneticTestingOrder testingOrder = orderRepository.findById(geneticTestingOrderAddtionB
                .getGeneticTestingOrderId());
        if (testingOrder != null) {
            if (testingOrder.getStatus() != null && OrderStatus.WAIT_RECEIPT_MONEY.getCode() != testingOrder
                    .getStatus()) {
                return new ApiResult(5001, "failed", "非待付款订单不能进行此操作", null);
            }
        }
        //将订单状态改为“订单待完善”,同时更新订单支付状态
        orderRepository.updateOrderForUnderlinePay(geneticTestingOrderAddtionB.getGeneticTestingOrderId(),
                OrderStatus.WAIT_PERFECTED.getCode(), OrderChargeStatus.CHARGED.getValue(), new Date());
        //orderRepository.updateTestingOrderAddTionB(geneticTestingOrderAddtionB);
        //生成订单支付信息
        GeneticTestingOrderPayment orderPayment = new GeneticTestingOrderPayment();
        ApiResult<GeneratorDto> generator = generatorService.getGenerator("genetic_testing_order)payment", null);
        orderPayment.setId(generator.getData().getSerialNumber());
        orderPayment.setOrderId(geneticTestingOrderAddtionB.getGeneticTestingOrderId());
        orderPayment.setBusinessType(PaymentBusinessType.GENETIC_TESTING.getCode());
        orderPayment.setPaymentNo(geneticTestingOrderAddtionB.getTransactionNo());
        orderPayment.setPaymentWay(PayType.UNDERLINE_PAY.getValue());
        orderPayment.setPaymentChannel(PaymentChannelType.UNDERLINE_PAY.getCode());
        orderPayment.setPaymentAmount(geneticTestingOrderAddtionB.getOriginalCost());
        orderPayment.setPaymentStatus(PaymentIntStatus.PAID.getCode());
        orderPayment.setPaymentDateTime(new Date());
        orderPayment.setPaymentVoucher(geneticTestingOrderAddtionB.getPaymentImageUrl());
        orderPayment.setRemarks(geneticTestingOrderAddtionB.getRemarks());
        orderPayment.setDeleteFlag(0);
        orderPayment.setUpdateDateTime(orderPayment.getPaymentDateTime());
        orderRepository.insertOrderPayMent(orderPayment);
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(geneticTestingOrderAddtionB.getGeneticTestingOrderId());
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setStatus(OrderStatus.WAIT_RECEIPT_MONEY.getCode());
        orderOperationDetail.setDescription("线下收款");
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
        return new ApiResult(200, "success", "保存成功", null);
    }

    /**
     * 付款待分配订单列表
     *
     * @param condition 查询条件
     * @return
     */
    @Override
    public ApiResult distributeOrders(DistributeOrderCondition condition) {
        FieldChecker.checkEmpty(condition.getLimitHelper(), "分页条件");
        if (StringUtils.isEmpty(condition.getSortType())) {
            condition.setSortType("asc");
        }
        int count = 0;
        List<Integer> integers = orderRepository.distributeOrderCount(condition);
        if (integers != null && integers.size() > 0) {
            count = integers.size();
        }
        Pagination<DistributeOrdersDto> pagination = Pagination.newInstance(condition.getLimitHelper(), count);
        List<DistributeOrdersDto> distributeOrdersDtos = new ArrayList<>();
        if (count > 0) {
            distributeOrdersDtos = orderRepository.distributeOrders(condition);
            if (distributeOrdersDtos != null && distributeOrdersDtos.size() > 0) {
                int rowNum = (condition.getLimitHelper().getPage() - 1) * condition.getLimitHelper().getSize();
                for (int i = 0; i < distributeOrdersDtos.size(); i++) {
                    DistributeOrdersDto distributeOrdersDto = distributeOrdersDtos.get(i);
                    distributeOrdersDto.setNumber(rowNum + 1 + i);
                    //状态转换
                    distributeOrdersDto.setStatusDesc(OrderStatus.getEnum(distributeOrdersDto.getStatus()).getDesc());
                }
            }
        }
        pagination.setResult(distributeOrdersDtos);
        return new ApiResult(200, "success", "数据获取成功", pagination);
    }

    /**
     * @Description 待分配订单详情
     * @Author jcl
     * @CreateDate 2018/10/16 17:37
     * @Param id 订单id
     * @Return
     */
    @Override
    public ApiResult distributeOrderDetail(String id) {
        DistributeOrderDetailInfoDto distributeOrderDetailInfo = orderRepository.distributeOrderDetail(id);
        //收货地址处理
        String consigneeAddress = distributeOrderDetailInfo.getConsigneeAddress();
        consigneeAddress = (distributeOrderDetailInfo.getProvinceName() == null ? "" : distributeOrderDetailInfo
                .getProvinceName())
                + (distributeOrderDetailInfo.getCityName() == null ? "" : distributeOrderDetailInfo
                .getCityName())
                + (distributeOrderDetailInfo.getDistrictName() == null ? "" : distributeOrderDetailInfo
                .getDistrictName())
                + (consigneeAddress == null ? "" : consigneeAddress);
        distributeOrderDetailInfo.setConsigneeAddress(consigneeAddress);
        //检测证明图片处理
        if (!StringUtils.isEmpty(distributeOrderDetailInfo.getTestingProofImagesUrl())) {
            JSONArray jsonArray = JSONObject.parseArray(distributeOrderDetailInfo.getTestingProofImagesUrl());
            String[] s = new String[jsonArray.size()];
            s = jsonArray.toArray(s);
            if (s != null && s.length > 0) {
                List<String> imageList = Arrays.asList(s);
                if (imageList != null && imageList.size() > 0) {
                    List<String> qiniuImageList = QiniuCertificateUtil.getDownloadCertificateList(imageList);
                    distributeOrderDetailInfo.setTestingProofImagesUrls(qiniuImageList);
                }
            }
        }
        if (distributeOrderDetailInfo.getDistributeOrderTestInfoDto() != null) {
            //性别状态码转换为中文
            if (distributeOrderDetailInfo.getDistributeOrderTestInfoDto().getPatientSex() != null) {
                distributeOrderDetailInfo.getDistributeOrderTestInfoDto().setPatientSexDesc(SexType.sex
                        (distributeOrderDetailInfo.getDistributeOrderTestInfoDto().getPatientSex()));
            }
            if (distributeOrderDetailInfo.getDistributeOrderTestInfoDto().getInvoiceType() != null) {
                //如果发票类型是个人类型，抬头名称为个人名称
                if (distributeOrderDetailInfo.getDistributeOrderTestInfoDto().getInvoiceType() == 0) {
                    distributeOrderDetailInfo.getDistributeOrderTestInfoDto().setCompanyName
                            (distributeOrderDetailInfo.getDistributeOrderTestInfoDto().getPersonName());
                }
            }
            //取样地址处理
            DistributeOrderTestInfoDto orderTestInfoDto = distributeOrderDetailInfo.getDistributeOrderTestInfoDto();
            String testPersonAddress = orderTestInfoDto.getTestPersonAddress();
            testPersonAddress = (orderTestInfoDto.getProvinceName() == null ? "" : orderTestInfoDto.getProvinceName())
                    + (orderTestInfoDto.getCityName() == null ? "" : orderTestInfoDto.getCityName())
                    + (orderTestInfoDto.getDistrictName() == null ? "" : orderTestInfoDto.getDistrictName())
                    + (testPersonAddress == null ? "" : testPersonAddress);
            orderTestInfoDto.setTestPersonAddress(testPersonAddress);
        }
        if (distributeOrderDetailInfo.getDistributeOrderPayInfoDto() != null) {
            if (distributeOrderDetailInfo.getDistributeOrderPayInfoDto().getPaymentWay() != null) {
                //如果是微信支付固定为微信二维码
                if (distributeOrderDetailInfo.getDistributeOrderPayInfoDto().getPaymentWay() == PayType.WECHAT
                        .getValue()) {
                    distributeOrderDetailInfo.getDistributeOrderPayInfoDto().setPaymentWayDesc("微信二维码");
                } else {
                    distributeOrderDetailInfo.getDistributeOrderPayInfoDto().setPaymentWayDesc(PayType.getEnum
                            (distributeOrderDetailInfo.getDistributeOrderPayInfoDto().getPaymentWay()).getDesc());
                }
            }
            if (distributeOrderDetailInfo.getDistributeOrderPayInfoDto().getPaymentStatus() != null) {
                //如果状态为已支付固定为支付成功
                if (distributeOrderDetailInfo.getDistributeOrderPayInfoDto().getPaymentStatus() == PaymentIntStatus
                        .PAID.getCode()) {
                    distributeOrderDetailInfo.getDistributeOrderPayInfoDto().setPaymentStatusDesc("支付成功");
                } else {
                    distributeOrderDetailInfo.getDistributeOrderPayInfoDto().setPaymentStatusDesc(PaymentIntStatus
                            .getEnum(distributeOrderDetailInfo.getDistributeOrderPayInfoDto().getPaymentStatus())
                            .getDesc
                                    ());
                }
            }
        }
        //处理商品图片
        if (distributeOrderDetailInfo.getDistributeOrderPackageInfoDtos() != null && distributeOrderDetailInfo
                .getDistributeOrderPackageInfoDtos().size() > 0) {
            List<DistributeOrderPackageInfoDto> packageInfoDtos = distributeOrderDetailInfo
                    .getDistributeOrderPackageInfoDtos();
            for (DistributeOrderPackageInfoDto packageInfoDto : packageInfoDtos) {
                if (!StringUtils.isEmpty(packageInfoDto.getImagesUrl())) {
                    packageInfoDto.setImagesUrl(QiniuCertificateUtil.getDownloadCertificateStr(packageInfoDto
                            .getImagesUrl()));
                }
                if (packageInfoDto.getDetectionPrice() != null && packageInfoDto.getDiscountPrice() != null) {
                    packageInfoDto.setDetectionPrice(packageInfoDto.getDetectionPrice().subtract(packageInfoDto
                            .getDiscountPrice()));
                }
            }
            distributeOrderDetailInfo.setDistributeOrderPackageInfoDtos(packageInfoDtos);
        }
        return new ApiResult(200, "success", "数据获取成功", distributeOrderDetailInfo);
    }

    /***
     * @Description 给订单分配地服
     * @Author jcl
     * @CreateDate 2018/10/18 15:43
     * @param orderId 订单id
     * @Param distributorId 分配人员id
     * @Param assigneeId 地服id
     * @Return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult distributeDifu(String orderId, String distributorId, String assigneeId) {
        orderRepository.distributeDifu(orderId, distributorId, assigneeId, OrderStatus.INIT.getCode(), new Date());
        orderRepository.updateOrderA(orderId, assigneeId);
        return new ApiResult(200, "success", "分配成功", null);
    }

    /**
     * @param platformOrder 订单信息
     * @param userId        用户id
     * @return void
     * @description 修改平台订单信息
     * @author maodi
     * @createDate 2018/11/5 14:14
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public int updatePlatformOrder(PlatformOrderDto platformOrder, String userId) {
        int count = 0;
        count += consoleOrderRepository.updatePlatformOrder(platformOrder);
        count += consoleOrderRepository.updatePlatformOrderAddtionA(platformOrder);
        //保存操作记录
        String orderId = platformOrder.getOrderId();
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderId);
        orderOperationDetail.setOperatorId(userId);
        Integer status = orderRepository.getOrderStatusByOrderId(orderId);
        orderOperationDetail.setStatus(status);
        String doctorId = platformOrder.getDoctorId();
        if (StringUtils.isNotBlank(doctorId)) {
            orderOperationDetail.setDescription("修改订单医生");
        } else {
            orderOperationDetail.setDescription("修改订单信息");
        }
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
        return count;
    }

    /**
     * @param orderId 订单id
     * @return int
     * @description 查询当前订单是否在待地管确认状态 ~ 发票待确认状态之间（包含临界值）
     * @author maodi
     * @createDate 2018/11/5 16:03
     */
    @Override
    public int isStatus(String orderId) {
        return consoleOrderRepository.isStatus(orderId);
    }

    /**
     * @param orderId 订单id
     * @return int
     * @description 查询订单医生是否已经修改
     * @author maodi
     * @createDate 2018/11/6 9:19
     */
    @Override
    public int queryIsChangedDoctor(String orderId) {
        return consoleOrderRepository.queryIsChangedDoctor(orderId);
    }

    /**
     * 平台端确认样本弹窗信息获取
     *
     * @param orderId 订单id
     * @return
     * @author jcl
     * @date 2018/11/8 15:38
     */
    @Override
    public ApiResult sampleConfirmInfo(String orderId) {
        List<OrderSampleConfirmDto> sampleConfirmDtos = consoleOrderRepository.sampleConfirmInfo(orderId);
        if (sampleConfirmDtos != null && sampleConfirmDtos.size() > 0) {
            for (OrderSampleConfirmDto sampleConfirmDto : sampleConfirmDtos) {
                //状态值处理
                if (sampleConfirmDto.getStatus() != null) {
                    sampleConfirmDto.setStatusDesc(OrderPackageStatus.desc(sampleConfirmDto.getStatus()));
                }
                if (StringUtils.isNotEmpty(sampleConfirmDto.getCourierCompanyName())) {
                    sampleConfirmDto.setCourierCompanyName(ExpressCompanyType.getEnum(sampleConfirmDto
                            .getCourierCompanyName()).getDesc());
                }
                //样本信息处理
                if (!StringUtils.isEmpty(sampleConfirmDto.getSampleIds())) {
                    ApiResult<List<GeneticTestingSampleDto>> samples = sampleService.getSamplesByIds(sampleConfirmDto
                            .getSampleIds());
                    if (samples.isSucc()) {
                        if (samples.getData() != null) {
                            List<GeneticTestingSampleDto> sampleDtos = samples.getData();
                            if (sampleDtos != null && sampleDtos.size() > 0) {
                                StringBuffer sb = new StringBuffer();
                                for (GeneticTestingSampleDto sampleDto : sampleDtos) {
                                    sb.append(",").append(sampleDto.getLabel());
                                }
                                String sample = sb.deleteCharAt(0).toString();
                                sampleConfirmDto.setSamples(sample);
                            }
                        }
                    }
                }
                //处理是否寄回余蜡
                if (sampleConfirmDto.getIsSendWaxBlock() != null && sampleConfirmDto.getIsSendWaxBlock() == 1) {
                    sampleConfirmDto.setIsSendWaxBlockDesc("是");
                } else {
                    sampleConfirmDto.setIsSendWaxBlockDesc("否");
                }
            }
        }
        return new ApiResult(200, "success", "获取数据成功", sampleConfirmDtos);
    }

    /***
     * 确认样本
     * @author jcl
     * @date 2018/11/8 17:14
     * @param orderId 订单id
     * @param userId 确认人id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult sampleConfirm(String orderId, String userId, List<OrderSampleConfirmDto> params) {
        //修改状态前需要判断此订单目前是不是样本待确认状态
        GeneticTestingOrder testingOrder = orderRepository.findById(orderId);
        if (testingOrder != null) {
            if (OrderStatus.WAIT_SAMPLE_CONFIRM.getCode() != testingOrder.getStatus()) {
                return new ApiResult(5001, "failed", "只有样本待确认的订单才可进行此操作", null);
            }
        }
        //修改订单套餐状态
        if (params != null && params.size() > 0) {
            for (OrderSampleConfirmDto param : params) {
                if (param.getSignerDateTime() != null && param.getSignerDateTime().getTime() > System
                        .currentTimeMillis()) {
                    return new ApiResult(5001, "failed", param.getPackageName() + "的确认时间不能大于现在", null);
                }
                //验证是否是变更过的套餐
                GeneticTestingOrderAddtionA addtionA = orderRepository.findAddtionAByOrderId(param.getOrderId());
                if (addtionA.getPackageChangeFlag() != null) {
                    //变更未确认订单
                    if (addtionA.getPackageChangeFlag() == 0) {
                        return new ApiResult(13053, "failed", "“" + param.getPackageName() + "”" + "套餐变更未确认", null);
                    } else {
                        //变更已确认
                        ConsoleOrderInterchangeDto orderInterchangeDto = orderRepository.orderInterchange(param.getOrderId(), param.getPackageId());
                        if (orderInterchangeDto.getReplenishmentFlag() == 1 && orderInterchangeDto.getStatus() != 2) {
                            //未补款不能确认样本
                            return new ApiResult(13054, "failed", "“" + param.getPackageName() + "”" + "套餐变更未补款", null);
                        }
                    }
                }
            }
            for (OrderSampleConfirmDto param : params) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("orderId", orderId);
                paramMap.put("userId", userId);
                paramMap.put("dateTime", param.getSignerDateTime());
                paramMap.put("packageId", param.getPackageId());
                consoleOrderRepository.sampleConfirm(paramMap);
                // 发送订单超期检测消息
                orderPostponeService.orderSampleConfirmed(orderId, param.getPackageId());
            }
        }
        //修改订单状态
        orderRepository.updateTestingOrderStatus(orderId, 9, new Date());
        //添加操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderId);
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setStatus(OrderStatus.WAIT_SAMPLE_CONFIRM.getCode());
        orderOperationDetail.setDescription("确认样本");
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
        return new ApiResult(200, "success", "确认样本成功", null);
    }

    /**
     * 后台确认报告
     *
     * @param geneticTestingOrder
     * @param userId
     * @return
     * @author FX
     * @date 2018/11/8 14:57
     */
    @Override
    public ApiResult confirmationReport(GeneticTestingOrder geneticTestingOrder, String userId) {
        List<OrderPackage> packageList = orderPackageMapper.getPackageByOrderId(geneticTestingOrder.getId());
        //检验必须说确认变更过后的才能确认报告genetic_testing_order_package的package_confirm_flag不为null并且必须是1
        boolean b = packageList.stream().filter(c -> c.getPackageConfirmFlag() != null).anyMatch(c -> c.getPackageConfirmFlag() == 0);
        if(b){
            return ApiResult.fail(OrderErrorCode.CONFIRM_THE_CHANGE_FIRST);
        }
        List<Map<String, Object>> collect = packageList.stream()
                .filter(c -> c.getStatus() != null && c.getStatus() == 2)
                .map(orderPackage -> {
                    //申请单号
                    String requisitionNo = agencyOrderRepository.queryRequisition(orderPackage.getGeneticTestingAgencyId
                            (), orderPackage.getGeneticTestingOrderId());
                    Map<String, Object> map = new HashMap<>();
                    map.put("orderId", geneticTestingOrder.getId());
                    map.put("packageId", orderPackage.getPackageId());
                    map.put("orderPackageId", orderPackage.getId());
                    map.put("orderPackageName", orderPackage.getPackageName());
                    map.put("requisitionNo", requisitionNo);
                    return map;
                }).collect(Collectors.toList());
        if (collect.size() > 0) {
            return ApiResult.fail(OrderErrorCode.THE_REPORT_FOR_THIS_ORDER_WAS_NOT_ALL_UPLOADED, collect);
        }
        //确认完成后，可发放积分
        consoleOrderRepository.updateOrderAPointSend(geneticTestingOrder.getId());
        orderRepository.updateTestingOrderStatus(geneticTestingOrder.getId(), OrderStatus.PAID_FOR.getCode(), new
                Date());
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(geneticTestingOrder.getId());
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setStatus(OrderStatus.DIFU_CONFIRMED.getCode());
        orderOperationDetail.setDescription("地管确认");
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
        return ApiResult.succ();
    }

    /***
     * 平台订单地管确认
     * @author jcl
     * @date 2018/11/9 9:39
     * @param orderId 订单id
     * @param confirm 审核内容
     * @param userId 用户id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult groundManageConfirm(String orderId, Map<String, Object> confirm, String userId) {
        GeneticTestingOrder testingOrder = orderRepository.findById(orderId);
        //修改状态前需要判断此订单是否是可确认的订单
        if (testingOrder != null) {
            Integer orderOldStatus = testingOrder.getStatus();
            if (OrderStatus.DIFU_CONFIRMED.getCode() != orderOldStatus) {
                return new ApiResult(5001, "failed", "只有待地管确认的订单才可进行此操作", null);
            }
        }
        if (confirm.get("status") != null) {
            int status = (int) confirm.get("status");
            //如果是商城来源的订单，不可拒绝
            if (status == OrderStatus.REFUSE_EDIT.getCode()) {
                Object orderOrigin = confirm.get("orderOrigin");
                if (orderOrigin != null) {
                    int orderOrderOrigin = (int) orderOrigin;
                    if (orderOrderOrigin == ClientType.APP.getCode()
                            || orderOrderOrigin == ClientType.APPLETS.getCode()
                            || orderOrderOrigin == ClientType.PC.getCode()) {
                        return new ApiResult(5001, "failed", "来自商城的订单不能拒绝", null);
                    }
                }
            }
            String reason = null;
            if (confirm.get("reason") != null) {
                reason = String.valueOf(confirm.get("reason"));
            }
            //如果地管确认为通过，需要判断订单来源
            if (status == OrderStatus.WAIT_SAMPLE_CONFIRM.getCode()) {
                Object orderOrigin = confirm.get("orderOrigin");
                if (orderOrigin != null) {
                    int orderOrderOrigin = (int) orderOrigin;
                    if (orderOrderOrigin == ClientType.APP.getCode()
                            || orderOrderOrigin == ClientType.APPLETS.getCode()
                            || orderOrderOrigin == ClientType.PC.getCode()) {
                        //如果是商城来源的订单则将订单状态改为 订单待完善
                        status = OrderStatus.WAIT_PERFECTED.getCode();
                    }
                }
            }
            orderRepository.groundManageConfirm(orderId, status, reason, new Date());
            //地管审核通过后生成申请单
            if (status == OrderStatus.WAIT_SAMPLE_CONFIRM.getCode() || status == OrderStatus.WAIT_PERFECTED.getCode()) {
                applyOrderService.addApplyOrder(orderId, "");
            }
            //保存操作记录
            GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
            orderOperationDetail.setOrderId(orderId);
            orderOperationDetail.setOperatorId(userId);
            orderOperationDetail.setStatus(OrderStatus.DIFU_CONFIRMED.getCode());
            orderOperationDetail.setDescription("地管确认");
            orderOperationDetail.setOrderType(1);
            orderService.orderOperationLog(orderOperationDetail);
        }
        return new ApiResult(200, "failed", "地管确认成功", null);
    }

    /***
     * 订单的套餐信息
     * @author jcl
     * @date 2018/11/13 10:55
     * @param orderId 订单id
     * @return
     */
    @Override
    public ApiResult orderPackages(String orderId) {
        List<OrderSampleConfirmDto> orderPackages = consoleOrderRepository.orderPackages(orderId);
        return new ApiResult(200, "success", "数据获取成功", orderPackages);
    }

    /***
     * 获取机构寄送的物品
     * @author jcl
     * @date 2018/12/21 17:42
     * @param orderId 订单id
     * @param packageId 套餐id
     * @return
     */
    @Override
    public ApiResult orderPackageSendItems(String orderId, String packageId) {
        String sendItems = consoleOrderRepository.sendItems(orderId, packageId);
        if (StringUtils.isNotEmpty(sendItems)) {
            String[] items = sendItems.split(",");
            List<String> itermList = Arrays.asList(items);
            Set set = new HashSet(itermList);
            return new ApiResult(200, "success", "获取数据成功", set);
        }
        return new ApiResult(200, "success", "获取数据成功", new HashSet<>());
    }

    /***
     * 平台端签收材料
     * todo jcl 统一返回格式与错误码，不要让错误码散乱到代码中
     *
     * @author jcl
     * @date 2018/11/13 11:32
     * @param orderPackageSign
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<NullObject> orderPackageSign(GeneticTestingOrderPackageSign orderPackageSign, String userId) {
        GeneticTestingOrder testingOrder = orderRepository.findById(orderPackageSign.getOrderId());
        //修改状态前需要判断此订单是否是可签收的订单
        if (testingOrder != null) {
            Integer orderOldStatus = testingOrder.getStatus();
            if (OrderStatus.MAIL.getCode() != orderOldStatus) {
                // return new ApiResult(5001, "failed", "只有待签收的订单才可进行此操作", null);
                return ApiResult.failFormatTip(OrderErrorCode.ORDER_MATERIAL_SIGN_EXCEPTION, "只有待签收的订单才可进行此操作");
            }
        }
        //判断签收日期是否大于今天
        Date signDateTime = orderPackageSign.getSignDateTime();
        FieldChecker.checkEmpty(signDateTime, "签收日期");
        if (signDateTime.getTime() > System.currentTimeMillis()) {
            // return new ApiResult(5001, "failed", "签收日期不能大于今天", null);
            return ApiResult.failFormatTip(OrderErrorCode.ORDER_MATERIAL_SIGN_EXCEPTION, "签收日期不能大于今天");
        }
        //判断签收日期是否小于最后寄送时间
        Date date = consoleOrderRepository.orderPackageSendDate(orderPackageSign.getOrderId(), orderPackageSign
                .getPackageId());
        if (date != null) {
            // fix BUG[19672] 签收材料弹框，当签收时间小于寄送时间可以签收成功
            // 计算两个日期之间间隔的天数，签收日期应该大于等于寄送日期
            if (SimpleDateUtils.durationDays(signDateTime, date) > 0) {
                // return new ApiResult(5001, "failed", "签收日期不能小于最后寄送日期", null);
                return ApiResult.failFormatTip(OrderErrorCode.ORDER_MATERIAL_SIGN_EXCEPTION, "签收日期不能小于最后寄送日期" +
                        SimpleDateUtils
                                .formatDate
                                        (date, SimpleDateUtils.DatePattern.YYYY_MM_DD));
            }
        }
        //保存签收信息
        ApiResult<GeneratorDto> generator = generatorService.getGenerator("order_package_sign", null);
        orderPackageSign.setId(generator.getData().getSerialNumber());
        consoleOrderRepository.orderPackageSign(orderPackageSign);
        //如果是最后一次签收则修改订单套餐状态
        if (orderPackageSign.getIsLastSign() == 1) {
            consoleOrderRepository.updateOrderPackageStatus(orderPackageSign.getOrderId(), orderPackageSign
                    .getPackageId(), 6);
            //如果该订单的所有套餐状态都为已完成则修改订单状态
            List<Integer> status = agencyOrderRepository.orderPackageStatus(orderPackageSign.getOrderId());
            if (status != null && status.size() == 1 && status.get(0) == 6) {
                orderRepository.updateTestingOrderStatus(orderPackageSign.getOrderId(), OrderStatus.WAIT_AGENCY_SEND
                        .getCode(), new Date());
            }
        }
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderPackageSign.getOrderId());
        orderOperationDetail.setOperatorId(orderPackageSign.getUserId());
        orderOperationDetail.setStatus(OrderStatus.MAIL.getCode());
        orderOperationDetail.setDescription("签收材料");
        orderOperationDetail.setOrderType(1);
        orderOperationDetail.setOperatorId(userId);
        orderService.orderOperationLog(orderOperationDetail);
        // return new ApiResult(200, "success", "签收材料成功", null);
        return ApiResult.succ(null, "签收材料成功");
    }

    /***
     * 结算列表查询
     * @author jcl
     * @date 2018/11/13 17:50
     * @param condition 查询条件
     * @return
     */
    @Override
    public ApiResult orderSettlementPage(SettlementCondition condition) {
        FieldChecker.checkEmpty(condition.getLimitHelper(), "分页条件不能为空");
        //判断时间结束时间是否小于开始时间，如果小于给出提示
        if (StringUtils.isNotEmpty(condition.getOrderStartTime()) && StringUtils.isNotEmpty(condition.getOrderEndTime
                ())) {
            Date startTime = SimpleDateUtils.parseDate(condition.getOrderStartTime(), SimpleDateUtils.DatePattern
                    .STANDARD_PATTERN.toString());
            Date endTime = SimpleDateUtils.parseDate(condition.getOrderEndTime(), SimpleDateUtils.DatePattern
                    .STANDARD_PATTERN.toString());
            if (startTime.getTime() > endTime.getTime()) {
                return new ApiResult(5001, "failed", "下单开始时间不能大于下单结束时间", null);
            }
        }
        //判断结算结束时间是否小于结算开始时间，如果小于给出提示
        if (StringUtils.isNotEmpty(condition.getSettlementStartTime()) && StringUtils.isNotEmpty(condition
                .getSettlementEndTime())) {
            Date startTime = SimpleDateUtils.parseDate(condition.getSettlementStartTime(), SimpleDateUtils
                    .DatePattern.STANDARD_PATTERN.toString());
            Date endTime = SimpleDateUtils.parseDate(condition.getSettlementEndTime(), SimpleDateUtils.DatePattern
                    .STANDARD_PATTERN.toString());
            if (startTime.getTime() > endTime.getTime()) {
                return new ApiResult(5001, "failed", "结算开始时间不能大于结算结束时间", null);
            }
        }

        //默认按照下单时间降序排序
        if (StringUtils.isEmpty(condition.getCreateTimeSort()) && StringUtils.isEmpty(condition.getCostSort())
                && StringUtils.isEmpty(condition.getCollectTimeSort()) && StringUtils.isEmpty(condition
                .getSettleTimeSort())) {
            condition.setCreateTimeSort("asc");
        }
        //查询列表数量
        Integer count = consoleOrderRepository.orderSettlementCount(condition);
        Pagination<OrderSettlementDto> pagination = Pagination.newInstance(condition.getLimitHelper(), count);
        List<OrderSettlementDto> orderSettlements = new ArrayList<>();
        if (count > 0) {
            orderSettlements = consoleOrderRepository.orderSettlements(condition);
            if (orderSettlements != null && orderSettlements.size() > 0) {
                int rowNum = (condition.getLimitHelper().getPage() - 1) * condition.getLimitHelper().getSize();
                for (int i = 0; i < orderSettlements.size(); i++) {
                    OrderSettlementDto orderSettlementDto = orderSettlements.get(i);
                    orderSettlementDto.setNumber(rowNum + i + 1);
                }
            }
        }
        pagination.setResult(orderSettlements);
        return new ApiResult(200, "success", "基因检测结算列表查询成功", pagination);
    }

    /**
     * 基因检测结算
     *
     * @param orderPackage
     * @return
     * @author FX
     * @date 2018/11/14 17:37
     */
    @Override
    public ApiResult settleAccounts(OrderPackage orderPackage) {

        OrderPackage orderPackage1 = orderPackageMapper.selectByPackageIdAndOrder(orderPackage);
        if (orderPackage1.getCost() == null) {
            return ApiResult.fail(OrderErrorCode.DETECTION_COST_CANNOT_BE_EMPTY);
        }
        orderPackage.setSettlementStatus(2);
        orderPackage.setSettlementDateTime(new Date());
        orderPackageMapper.updateByPackageIdAndOrder(orderPackage);
        return ApiResult.succ();
    }

    /**
     * 批量结算
     *
     * @param orderPackage
     * @return
     * @author FX
     * @date 2018/11/15 13:46
     */
    @Override
    public ApiResult batchSettlement(List<OrderPackage> orderPackage) {
        if (orderPackage == null) {
            return ApiResult.fail(OrderErrorCode.BILLING_OBJECT_CANNOT_BE_EMPTY);
        }
        for (OrderPackage o : orderPackage) {
            OrderPackage orderPackage1 = orderPackageMapper.selectByPrimaryKey(o.getId());
            if (orderPackage1.getCost() == null) {
                return ApiResult.fail(OrderErrorCode.DETECTION_COST_CANNOT_BE_EMPTY);
            }
        }
        List<OrderPackage> collect = orderPackage.stream().peek(c -> {
            c.setSettlementStatus(2);
            c.setSettlementDateTime(new Date());
        }).collect(Collectors.toList());
        orderPackageMapper.updateByPrimaryKeyMore(collect);
        return ApiResult.succ();
    }

    /**
     * 获取结算列表
     *
     * @param con
     * @return
     */
    @Override
    public List<OrderSettlementDto> getOrderSettlements(SettlementCondition con) {
        return consoleOrderRepository.orderSettlements(con);
    }

    /**
     * 结算成本更新
     *
     * @param dataList
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public Boolean updateSettlementInfo(List<Map<String, Object>> dataList) {
        try {
            //订单套餐成本不为空，套餐检测机构成本为空，更新2个成本
            Integer result = consoleOrderRepository.updateSettlementInfo(dataList);
            return result == null || result >= 0;
        } catch (Exception e) {
            LOGGER.error("update is error...", e);
            return false;
        }
    }

    /**
     * 获取导出信息
     *
     * @param exportCondition 导出信息id
     * @return
     */
    @Override
    public List<OrderSettlementDto> getExportInfoByIds(SettlementExportCondition exportCondition) {
        //选择行为空，说明导出全部，否则导出选中行
        if (ExportType.SELECTED.getType().equals(exportCondition.getExportType())) {
            return consoleOrderRepository.getExportInfoByIds(exportCondition.getExportRowIds());
        }
        return consoleOrderRepository.exportAll(exportCondition);
    }

    /**
     * 修改成本
     *
     * @param orderPackage
     * @return
     * @author FX
     * @date 2018/11/15 11:07
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateCost(OrderPackage orderPackage) {
        orderPackageMapper.updateByPackageIdAndOrder(orderPackage);
        GeneticTestingProductDetail geneticTestingProductDetail = orderPackageMapper.getPackageCost(orderPackage);
        if (geneticTestingProductDetail != null && geneticTestingProductDetail.getCost() == null) {
            geneticTestingProductDetail.setCost(orderPackage.getCost());
            orderPackageMapper.updateProductDetailCost(geneticTestingProductDetail);
        }
        return ApiResult.succ();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<NullObject> deliveryToGroundServant(GeneticTestingExpressDelivery delivery) {
        FieldChecker.checkEmpty(delivery, "寄送信息");
        checkParamsForServant(delivery);
        ApiResult<GeneticTestingUserAddress> addressResult = consignAddressService.findAddressInfo(delivery
                .getUserAddressId());
        if (!addressResult.isSucc()) {
            return ApiResult.fail(addressResult.getError());
        }
        delivery.setDetailAddress(addressResult.getData().getAddress());

        GeneticTestingOrder order = orderRepository.findById(delivery.getOrderId());
        if (order == null || DeleteFlagType.DELETE.getCode() == order.getDeleteFlag()) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }
        OrderStatus currentStatus = OrderStatus.getEnum(order.getStatus());
        if (!OrderStatus.WAIT_AGENCY_SEND.equals(currentStatus)) {
            return ApiResult.fail(OrderErrorCode.ORDER_STATUS_EXCEPTION_FOR_DELIVERY_TO_SERVANT);
        }
        delivery.setId(UUID32.randomUUIDString());
        delivery.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        delivery.setStatus("init");
        delivery.setType(1);
        // 最后一次寄送更新订单状态
        if (1 == delivery.getIsEnds()) {
            orderRepository.updateTestingOrderStatus(order.getId(), OrderStatus.WAIT_DIFU_SIGNING.getCode(), new Date
                    ());
        }
        expressDeliveryRepository.save(delivery);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<List<AddressDetails>> queryOrderServantAddress(String orderId) {
        GeneticTestingOrder order = orderRepository.findById(orderId);
        if (order == null || DeleteFlagType.DELETE.getCode() == order.getDeleteFlag()) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }
        GeneticTestingOrderAddtionA addtionA = orderRepository.findAddtionAByOrderId(orderId);
        if (addtionA == null) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }
        if (StringUtils.isBlank(addtionA.getUserId())) {
            return ApiResult.succ();
        }
        ApiResult<GeneticTestingUserAddressDetails> addressDetailsApiResult = consignAddressService
                .queryAddressDetails(addtionA.getUserId());
        if (!addressDetailsApiResult.isSucc()) {
            return ApiResult.fail(addressDetailsApiResult.getError());
        }
        GeneticTestingUserAddressDetails details = addressDetailsApiResult.getData();
        if (details == null) {
            return ApiResult.succ();
        }
        return ApiResult.succ(details.getAddresses());
    }

    /**
     * 寄送材料给地服参数校验
     */
    public void checkParamsForServant(GeneticTestingExpressDelivery delivery) {
        FieldChecker.checkEmpty(delivery.getOrderId(), "订单id");
        FieldChecker.checkEmpty(delivery.getUserAddressId(), "寄送地址");
        FieldChecker.checkEmpty(delivery.getCourierType(), "寄送类型");
        FieldChecker.checkEmpty(delivery.getCourierCompanyId(), "快递公司");
        // fix[19684] 有id匹配改为label匹配
        if (!"人工物流".equalsIgnoreCase(delivery.getCourierCompanyName())) {
            FieldChecker.checkMaxLength(delivery.getCourierNo(), 64, "快递单号");
        }
        FieldChecker.checkEmpty(delivery.getCourierDateTime(), "寄送时间");
        FieldChecker.checkEmpty(delivery.getIsEnds(), "是否为最后一次寄送");
        if (StringUtils.isNotBlank(delivery.getRemarks())) {
            FieldChecker.checkMaxLength(delivery.getRemarks(), 255, "备注");
        }
    }

    /**
     * @param orderId 订单id
     * @return com.hsgene.order.dto.console.OrderUpdateDto
     * @description 根据订单id获取订单修改信息
     * @author maodi
     * @createDate 2018/11/27 14:15
     */
    @Override
    public OrderUpdateDto queryOrderUpdate(String orderId) {
        return consoleOrderRepository.queryOrderUpdate(orderId);
    }

    /***
     * 订单详情
     * @author jcl
     * @date 2018/11/27 15:36
     * @param orderId 订单id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<OrderBaseInfo> consoleOrderDetail(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
        }
        OrderBaseInfo orderBaseInfo = consoleOrderRepository.orderDetail(orderId);
        //处理检测目的枚举值
        if (StringUtils.isNotEmpty(orderBaseInfo.getTestingPurpose())) {
            orderBaseInfo.setTestingPurpose(TestPurposeType.getEnmu(orderBaseInfo.getTestingPurpose()).getDesc());
        }
        //按钮显示控制
        showButton(orderBaseInfo);
        //订单流程处理
        orderStatusPosition(orderBaseInfo);
        //操作记录
        if (orderBaseInfo.getOrderOperationDetailInfos() != null && orderBaseInfo.getOrderOperationDetailInfos().size
                () > 0) {
            List<OrderOperationDetailInfo> operationDetailInfos = orderBaseInfo.getOrderOperationDetailInfos();
            for (OrderOperationDetailInfo operationDetailInfo : operationDetailInfos) {
                if (operationDetailInfo.getStatus() != null) {
                    operationDetailInfo.setStatusDesc(OrderStatus.getEnum(operationDetailInfo.getStatus()).getDesc());
                }
            }
        }
        //患者信息
        if (orderBaseInfo.getOrderPatientInfo() != null) {
            buildPatientAddress(orderBaseInfo.getOrderPatientInfo());
        }
        //订单套餐
        List<OrderPackageInfo> orderPackageInfos = orderBaseInfo.getOrderPackageInfos();
        //价格计算
        orderPriceCalculation(orderBaseInfo, orderPackageInfos);
        //如果订单状态为待收款，不展示订单实际价格和增项费用
        orderAdditionalPrice(orderBaseInfo);
        GeneticTestingOrder order = orderRepository.findById(orderId);
        //订单套餐
        if (orderPackageInfos != null && orderPackageInfos.size() > 0) {
            orderPackageInfos.forEach(c -> {
                //报告信息
                OrderPackageDetailInfo orderPackageDetailInfo = getOrderPackageDetailInfo(orderId, c);
                c.setOrderPackageDetailInfo(orderPackageDetailInfo);
                //设置状态值描述
                setDescValue(order, c);
                //套餐服务获取套餐下机构的耗材图片
                ApiResult<GeneticTestingProductDetailDto> result = productService.packageTestingInfo(c.getPackageId()
                        , c.getGeneticTestingAgencyId());
                if (result.isSucc() && result.getData() != null) {
                    GeneticTestingProductDetailDto productDetailDto = result.getData();
                    c.setGoodsImage(productDetailDto.getGoodsImage());
                }
            });
        }
        // 订单支付信息
        orderPaymentInfo(orderId, orderBaseInfo);
        //图片处理
        orderImageMange(orderBaseInfo);
        orderBaseInfo.setOrderPackageInfos(orderPackageInfos);
        // 订单退款信息
        orderBaseInfo.setRefunds(buildOrderRefunds(orderBaseInfo));
        return ApiResult.succ(orderBaseInfo);
    }

    /***
     * 详情页按钮显示控制
     * @author jcl
     * @date 2019/1/22 10:18
     * @param orderBaseInfo
     * @return
     */
    private void showButton(OrderBaseInfo orderBaseInfo) {
        Integer status = orderBaseInfo.getStatus();
        Integer orderOrigin = orderBaseInfo.getOrderOrigin();
        //是否显示确认报告按钮
        int testingOrderStatusCount = consoleOrderRepository.testingOrderStatusCount(orderBaseInfo.getOrderId());
        //判断是否显示确认订单按钮（如果订单状态为报告待上传或者订单中存在报告待上传的套餐则显示确认报告按钮）
        if (status == OrderStatus.TESTING.getCode() || testingOrderStatusCount > 0) {
            orderBaseInfo.setConfirmReportBtn(1);
        }
        //判断是否显示修改价格按钮和变更套餐按钮
        if (orderOrigin.equals(ClientType.PEANUT.getCode())
                || orderOrigin.equals(ClientType.GOLD_COLORED_GLASS.getCode())) {
            //是否显示修改价格按钮（状态为待地管确认和确认待修改才显示修改价格按钮）
            if (status.equals(OrderStatus.DIFU_CONFIRMED.getCode())||status.equals(OrderStatus.REFUSE_EDIT.getCode())) {
                orderBaseInfo.setShowUpdatePriceBtn(1);
            }
            //是否显示变更套餐按钮（当状态为样本待确认和报告待上传之间的状态才）
            if (status.equals(OrderStatus.TESTING.getCode())
                    || status.equals(OrderStatus.WAIT_SAMPLE_CONFIRM.getCode())) {
                if (orderBaseInfo.getPackageChangeFlag() == null) {
                    orderBaseInfo.setShowChangePackageBtn(1);
                }
            }
        }

    }

    /**
     * 构建订单退款信息
     *
     * @param order 订单信息
     * @return 订单退款信息
     */
    private List<OrderRefundInfoDto> buildOrderRefunds(OrderBaseInfo order) {
        List<GeneticTestingOrderRefund> refunds = orderRefundRepository.queryOrderRefunds(order.getOrderId());
        if (!CollectionUtils.isEmpty(refunds)) {
            return refunds.stream().map(e -> {
                OrderRefundInfoDto info = new OrderRefundInfoDto();
                info.setOrderId(order.getOrderId());
                info.setOrderNo(order.getOrderNo());
                info.setRefundReason(e.getRefundReason());
                info.setTotalRefundAmount(e.getRefundMoney());
                if (StringUtils.isNotBlank(e.getRefundVouchers())) {
                    info.setRefundVouchers(JsonUtils.jsonToObject(e.getRefundVouchers(), new
                            TypeReference<List<String>>() {
                            }));
                }
                if (StringUtils.isNotBlank(e.getRefundDetails())) {
                    info.setRefundPackages(JsonUtils.jsonToObject(e.getRefundDetails(), new
                            TypeReference<List<OrderRefundPackageDto>>() {
                            }));
                }
                return info;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 订单增项费用处理
     *
     * @param orderBaseInfo
     */
    private void orderAdditionalPrice(OrderBaseInfo orderBaseInfo) {
        if (orderBaseInfo.getOrderOrigin().equals(ClientType.PEANUT.getCode()) || orderBaseInfo.getOrderOrigin()
                .equals(ClientType.GOLD_COLORED_GLASS.getCode())) {
            if (orderBaseInfo.getStatus() != null) {
                if (orderBaseInfo.getStatus().equals(OrderStatus.INIT.getCode()) || orderBaseInfo.getStatus().equals
                        (OrderStatus.WAIT_RECEIPT_MONEY.getCode())) {
                    orderBaseInfo.setTotalCharges(null);
                }
                if (orderBaseInfo.getExceptionPosition() != null) {
                    if (orderBaseInfo.getExceptionPosition().equals(OrderStatus.INIT.getCode()) || orderBaseInfo
                            .getExceptionPosition().equals(OrderStatus.WAIT_RECEIPT_MONEY.getCode())) {
                        orderBaseInfo.setTotalCharges(null);
                    }
                }
            }
        }
        //增项费用(实际减应收)
        if (orderBaseInfo.getTotalCharges() != null && orderBaseInfo.getReceivablePrice() != null) {
            orderBaseInfo.setAdditionalCost(orderBaseInfo.getTotalCharges().subtract(orderBaseInfo.getReceivablePrice
                    ()));
        }
    }

    /**
     * 各种订单图片处理
     *
     * @param orderBaseInfo
     */
    private void orderImageMange(OrderBaseInfo orderBaseInfo) {
        //快递回单图片处理
        if (StringUtils.isNotEmpty(orderBaseInfo.getCourierImagesUrl())) {
            orderBaseInfo.setCourierImagesUrl(peanutQiniuBucket + orderBaseInfo.getCourierImagesUrl());
        }
        //检测证明集合图片凭证（如果是商城来源的订单则显示检测证明图片，如果是非商城的订单则显示检测图片）
        if (StringUtils.isNotEmpty(orderBaseInfo.getTestingProofImagesUrl())) {
            List<String> qiniuImageList = getStrings(orderBaseInfo.getTestingProofImagesUrl());
            orderBaseInfo.setTestingProofImagesUrls(qiniuImageList);
        } else if (StringUtils.isNotEmpty(orderBaseInfo.getTestingImagesUrl())) {
            List<String> peanutImages = peanutImages(orderBaseInfo.getTestingImagesUrl());
            orderBaseInfo.setTestingProofImagesUrls(peanutImages);
        }
        //样本图片集合图片凭证
        if (StringUtils.isNotEmpty(orderBaseInfo.getCollectSampleImagesUrl())) {
            List<String> peanutImages = peanutImages(orderBaseInfo.getCollectSampleImagesUrl());
            orderBaseInfo.setCollectSampleImagesUrls(peanutImages);
        }
        //dcw图片处理
        if (orderBaseInfo.getOrderDcwInfo() != null) {
            OrderDcwInfo orderDcwInfo = orderBaseInfo.getOrderDcwInfo();
            if (StringUtils.isNotEmpty(orderDcwInfo.getDcwImagesUrl())) {
                List<String> peanutImages = peanutImages(orderDcwInfo.getDcwImagesUrl());
                orderDcwInfo.setDcwImagesUrls(peanutImages);
            }
            if (StringUtils.isNotEmpty(orderDcwInfo.getYizhuImagesUrl())) {
                List<String> peanutImages = peanutImages(orderDcwInfo.getYizhuImagesUrl());
                orderDcwInfo.setYizhuImagesUrls(peanutImages);
            }
            if (StringUtils.isNotEmpty(orderDcwInfo.getImageInspectionImagesUrl())) {
                List<String> peanutImages = peanutImages(orderDcwInfo.getImageInspectionImagesUrl());
                orderDcwInfo.setImageInspectionImagesUrls(peanutImages);
            }
            if (StringUtils.isNotEmpty(orderDcwInfo.getBloodInspectionImagesUrl())) {
                List<String> peanutImages = peanutImages(orderDcwInfo.getBloodInspectionImagesUrl());
                orderDcwInfo.setBloodInspectionImagesUrls(peanutImages);
            }
        }
    }

    /**
     * 订单支付信息处理
     *
     * @param orderId
     * @param orderBaseInfo
     */
    private void orderPaymentInfo(String orderId, OrderBaseInfo orderBaseInfo) {
        List<GeneticTestingOrderPayment> payments = orderPaymentRepository.querySuccessPayment(orderId, null);
        if (!CollectionUtils.isEmpty(payments)) {
            orderBaseInfo.setOrderPaymentInfo(
                    payments.stream().map(payment -> {
                        OrderPaymentInfo info = new OrderPaymentInfo();
                        info.setRemarks(payment.getRemarks());
                        info.setPaymentNo(payment.getPaymentNo());
                        info.setPaymentAmount(payment.getPaymentAmount());
                        if (payment.getPaymentChannel() != null) {
                            info.setPaymentChannel(PaymentChannelType.getEnum(payment.getPaymentChannel()).getDesc());
                        }
                        info.setPaymentDateTime(payment.getPaymentDateTime());
                        if (payment.getPaymentStatus() != null) {
                            info.setPaymentStatusDesc(PaymentStatus.getEnum(payment.getPaymentStatus()).getDesc());
                        }
                        if (StringUtils.isNotBlank(payment.getPaymentVoucher())) {
                            info.setPaymentVouchers(Lists.newArrayList(payment.getPaymentVoucher().split(",")));
                        }
                        return info;
                    }).collect(Collectors.toList()));
        }
    }

    /**
     * 订单价格计算
     *
     * @param orderBaseInfo
     * @param orderPackageInfos
     */
    private void orderPriceCalculation(OrderBaseInfo orderBaseInfo, List<OrderPackageInfo> orderPackageInfos) {
        BigDecimal bigDecimal = BigDecimal.ZERO;
        Integer totalCommission = 0;
        if (orderPackageInfos != null && orderPackageInfos.size() > 0) {
            for (OrderPackageInfo o : orderPackageInfos) {
                //计算非终止状态的套餐总价和总佣金
                if ((o.getStatus() != null && o.getStatus() != 8) || (o.getStatus() == null)) {
                    //只有未变更过的套餐或者变更已确认完成的订单才计算价应收价格
                    if(o.getPackageConfirmFlag() == null || o.getPackageConfirmFlag() == 1){
                        //计算套餐总价值
                        BigDecimal packagePrice = o.getPackagePrice();
                        if (packagePrice == null) {
                            bigDecimal = bigDecimal.add(BigDecimal.ZERO);
                        } else {
                            bigDecimal = bigDecimal.add(packagePrice);
                        }
                        //计算套餐总佣金
                        Integer commission = o.getCommission();
                        if (commission != null) {
                            totalCommission = totalCommission + commission;
                        }
                    }
                } else {
                    continue;
                }
            }
            orderBaseInfo.setReceivablePrice(bigDecimal);
            orderBaseInfo.setTotalCommission(totalCommission);
        } else {
            orderBaseInfo.setTotalCommission(null);
        }
    }

    /**
     * 订单流程处理
     *
     * @param orderBaseInfo
     */
    private void orderStatusPosition(OrderBaseInfo orderBaseInfo) {
        //商城订单
        if (orderBaseInfo.getOrderOrigin() == 4
                || orderBaseInfo.getOrderOrigin() == 5
                || orderBaseInfo.getOrderOrigin() == 6) {
            //填充医生信息
            if (orderBaseInfo.getOrderDoctorInfo() != null) {
                orderBaseInfo.getOrderDoctorInfo().setDoctorName("虚拟医生");
            }
            //如果此订单是异常订单
            if (orderBaseInfo.getExceptionPosition() != null) {
                orderBaseInfo.setPosition(MallRoute.getPosition(orderBaseInfo.getExceptionPosition()).getPosition() +
                        1);
                orderBaseInfo.setExceptionOrder(true);
            } else {
                orderBaseInfo.setPosition(MallRoute.getPosition(orderBaseInfo.getStatus()).getPosition());
            }
        } else {
            //非商城订单
            // 填充订单医生信息
            fillOrderDoctorInfo(orderBaseInfo.getOrderId(), orderBaseInfo.getOrderDoctorInfo());
            //如果此订单是异常订单
            if (orderBaseInfo.getExceptionPosition() != null) {
                orderBaseInfo.setPosition(NotMallRoute.getPosition(orderBaseInfo.getExceptionPosition()).getPosition
                        () + 1);
                orderBaseInfo.setExceptionOrder(true);
            } else {
                orderBaseInfo.setPosition(NotMallRoute.getPosition(orderBaseInfo.getStatus()).getPosition());
            }
        }
    }

    /**
     * 患者地址处理
     *
     * @param orderPatientInfo
     */
    private void buildPatientAddress(OrderPatientInfo orderPatientInfo) {
        String provinceName = StringUtils.isEmpty(orderPatientInfo.getProvinceName()) ? "" : orderPatientInfo
                .getProvinceName();
        String cityName = StringUtils.isEmpty(orderPatientInfo.getCityName()) ? "" : orderPatientInfo.getCityName();
        String districtName = StringUtils.isEmpty(orderPatientInfo.getDistrictName()) ? "" : orderPatientInfo
                .getDistrictName();
        String address = StringUtils.isEmpty(orderPatientInfo.getPatientAddress()) ? "" : orderPatientInfo
                .getPatientAddress();
        orderPatientInfo.setPatientAddress(provinceName + cityName + districtName + address);
    }

    /**
     * 填充订单医生信息
     *
     * @param orderId 订单id
     * @param info    医生信息
     */
    private void fillOrderDoctorInfo(String orderId, OrderDoctorInfo info) {
        if (info != null && info.getDoctorId() != null) {
            Map<String, Object> doctorMap = userAuthenticationService.userAuthVerify(info.getDoctorId());
            if (CollectionUtils.isEmpty(doctorMap)) {
                LOGGER.error("获取订单[{}]关联医生给[{}]信息失败", orderId, info.getDoctorId());
            } else {
                info.setPost((String) doctorMap.get("postName"));
                info.setHospital((String) doctorMap.get("hospital"));
                info.setAddress(buildWholeDoctorAddress(doctorMap));
                String doctorName = (String) doctorMap.get("name");
                String doctorPhone = (String) doctorMap.get("phone");
                // 接口医生信息返回与订单医生数据判断是否一致，不一致则批量更新订单关联医生信息
                boolean doctorInfoChanged = false;
                // 医生名称不一致，取接口返回的信息，并更新订单医生数据
                if (StringUtils.isNotBlank(doctorName) && !doctorName.equals(info.getDoctorName())) {
                    info.setDoctorName(doctorName);
                    doctorInfoChanged = true;
                }
                // 医生电话号码不一致，取接口返回的信息，并更新订单医生数据
                if (StringUtils.isNotBlank(doctorPhone) && !doctorPhone.equals(info.getPhone())) {
                    info.setPhone(doctorPhone);
                    doctorInfoChanged = true;
                }
                if (doctorInfoChanged) {
                    consoleOrderRepository.updateBatchOrderDoctorInfo(info);
                }
            }

        }
    }

    private String buildWholeDoctorAddress(Map<String, Object> doctorMap) {
        String provinceName = doctorMap.get("provinceName") == null ? "" : (String) doctorMap.get("provinceName");
        String cityName = doctorMap.get("cityName") == null ? "" : (String) doctorMap.get("cityName");
        String districtName = doctorMap.get("districtName") == null ? "" : (String) doctorMap.get("districtName");
        String address = doctorMap.get("address") == null ? "" : (String) doctorMap.get("address");
        return provinceName + cityName + districtName + address;
    }


    private List<String> getStrings(String url) {
        try {
            JSONArray jsonArray = JSONObject.parseArray(url);
            List<String> imageList = JSONObject.parseArray(jsonArray.toJSONString(), String.class);
            return QiniuCertificateUtil.getDownloadCertificateList(imageList);
        } catch (Exception e) {
            LOGGER.error("json转换失败,url为【" + url + "】", e);
            e.printStackTrace();
        }
        return null;
    }

    private void setDescValue(GeneticTestingOrder order, OrderPackageInfo c) {
        //如果此套餐是变更过来的，展示的名称需要处理为“旧套餐名称-新套餐名称[操作：补差价(0.01)]”
        Integer actionType = consoleOrderRepository.changePackageActionType(order.getId(), c.getPackageId());
        if (actionType != null) {
            String packageTitle = c.getOldPackageName() + "-" + c.getPackageName();
            //如果是进行的补款操作才展示补款信息
            if (ActionType.SUPPLEMENT_AMOUNT.getCode().equals(actionType)
                    ||ActionType.SUPPLEMENT_SAMPLE_AMOUNT.getCode().equals(actionType)) {
                packageTitle = packageTitle + "[操作：" + ActionType.desc(actionType) + "(" + c.getSupplementAmount() +
                        ")]";
            } else {
                packageTitle = packageTitle + "[操作：" + ActionType.desc(actionType) + "]";
            }
            c.setPackageName(packageTitle);
        }
        //订单状态描述
        if (c.getStatus() != null) {
            c.setStatusDesc(OrderPackageStatus.desc(c.getStatus()));
        }
        //快递图片
        String courierImagesUrl = order.getCourierImagesUrl();
        if (StringUtils.isNotEmpty(courierImagesUrl)) {
            c.setCourierImagesUrls(peanutImages(courierImagesUrl));
        }
        //是否寄回描述
        if (c.getIsSendWaxBlock() != null && c.getIsSendWaxBlock() != 0) {
            c.setIsSendWaxBlockDesc("是");
            if (c.getIsSendWaxBlock() == 1) {
                c.setSendWaxBlockStatus("未寄回");
            } else {
                c.setSendWaxBlockStatus("已寄回");
            }
        } else if (c.getIsSendWaxBlock() != null && c.getIsSendWaxBlock() == 0) {
            c.setIsSendWaxBlockDesc("否");
        }
        //快递枚举描述
        if (StringUtils.isNotEmpty(c.getCourierCompanyName())) {
            c.setCourierCompanyName(ExpressCompanyType.getEnum(c.getCourierCompanyName()).getDesc());
        }

    }


    private OrderPackageDetailInfo getOrderPackageDetailInfo(String orderId, OrderPackageInfo c) {
        OrderPackageDetail orderPackageDetail = new OrderPackageDetail();
        orderPackageDetail.setPackageId(c.getPackageId());
        orderPackageDetail.setGeneticTestingOrderId(orderId);
        OrderPackageDetailInfo orderPackageDetailInfo = new OrderPackageDetailInfo();
        OrderPackageDetail packageDetail = packageDetailMapper.getDetailByOrderIdAndPackageId(orderPackageDetail);
        if (packageDetail != null) {
            BeanUtils.copyProperties(packageDetail, orderPackageDetailInfo);
            orderPackageDetailInfo.setPackageStatus(OrderPackageStatus.desc(c.getStatus()));
            //审核了，是否确认desc为是，未审核为否，是否被退回用审核通过未通过判断
            if (packageDetail.getReportAuditFlag() != null) {
                if (packageDetail.getReportAuditFlag() == ReportAduitStatus.PASS.getCode()) {
                    orderPackageDetailInfo.setReportRefused("否");
                } else if (packageDetail.getReportAuditFlag() == ReportAduitStatus.DIDNOTPASS.getCode()) {
                    orderPackageDetailInfo.setReportRefused("是");
                }
                orderPackageDetailInfo.setReportAuditDesc("是");
            } else {
                orderPackageDetailInfo.setReportAuditDesc("否");
            }
            if (StringUtils.isNotEmpty(packageDetail.getMolecular())) {
                ApiResult<SysDictDto> dtoApiResult = dictService.sysDict(packageDetail.getMolecular());
                if (200 == dtoApiResult.getCode() && dtoApiResult.getData() != null) {
                    orderPackageDetailInfo.setMolecular(dtoApiResult.getData().getValue());
                }
            }
            if (1 == packageDetail.getReportUploadFlag()) {
                orderPackageDetailInfo.setReportUploadFlag("是");
            } else if (0 == packageDetail.getReportUploadFlag()) {
                orderPackageDetailInfo.setReportUploadFlag("否");
            }
            if (StringUtils.isNotEmpty(packageDetail.getUploader())) {
                //上传者名称
                ApiResult<GeneticTestingOperationAccount> userInfo = userService.getUserInfo(packageDetail
                        .getUploader());
                orderPackageDetailInfo.setUploaderName(userInfo.getData().getRealName());
            }
            //报告图片七牛处理
            if (StringUtils.isNotEmpty(packageDetail.getReportUrl())) {
                orderPackageDetailInfo.setReportUrl(QiniuCertificateUtil.getDownloadCertificateStr(packageDetail
                        .getReportUrl()));
            }
        }
        return orderPackageDetailInfo;
    }

    /***
     * 花生仁图片处理
     * @author jcl
     * @date 2018/12/7 13:52
     * @param peanutImage
     * @return
     */
    private List<String> peanutImages(String peanutImage) {
        List<String> qiniuImageList = new ArrayList<>();
        String[] images = peanutImage.split(",");
        Arrays.stream(images).forEach(image -> {
            qiniuImageList.add(peanutQiniuBucket + image);
        });
        return qiniuImageList;
    }

    /**
     * 平台寄送给用户(只能是商城的订单和用户选择快递寄送)
     *
     * @param delivery
     * @return
     * @author FX
     * @date 2018/11/29 14:13
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<NullObject> sendToUser(GeneticTestingExpressDelivery delivery) {
        if (delivery.getCourierDateTime() != null) {
            if (delivery.getCourierDateTime().getTime() > System.currentTimeMillis()) {
                return new ApiResult<>(5001, "failed", "寄送日期不能大于今天", null);
            }
        }
        GeneticTestingOrder order = orderRepository.findById(delivery.getOrderId());
        if (order == null || DeleteFlagType.DELETE.getCode() == order.getDeleteFlag()) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }
        if (order.getOrderOrigin() != null) {
            int orderOrigin = order.getOrderOrigin();
            if (!(orderOrigin == (ClientType.APPLETS.getCode())
                    || orderOrigin == (ClientType.APP.getCode())
                    || orderOrigin == (ClientType.PC.getCode()))) {
                return ApiResult.fail(OrderErrorCode.ORDER_SOURCE_MUST_BE_PLATFORM);
            }
        }
        OrderStatus currentStatus = OrderStatus.getEnum(order.getStatus());
        if (!OrderStatus.WAIT_AGENCY_SEND.equals(currentStatus)) {
            return ApiResult.fail(OrderErrorCode.ORDER_STATUS_IS_NOT_ON_BEHALF_OF_DELIVERY);
        }
        delivery.setId(UUID32.randomUUIDString());
        delivery.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
        delivery.setStatus("init");
        delivery.setType(2);
        expressDeliveryRepository.save(delivery);
        //订单状态变为24-待收货
        orderRepository.updateTestingOrderStatusSendToUser(order.getId(), OrderStatus.WAIT_RECEIPT_GOODS.getCode(),
                new Date());
        // 发送自动收货定时消息
        sendAutoReceiptMsg(order.getId());
        return ApiResult.succ();
    }

    /**
     * 发送自动收货定时消息
     *
     * @param orderId 订单id
     */
    private void sendAutoReceiptMsg(String orderId) {
        Message msg = new Message(orderTopic, autoReceiptTag, orderId.getBytes());
        msg.setStartDeliverTime(calculateAutoReceiptDeliverTime());
        msg.setKey("AutoReceipt-" + UUID32.randomUUIDString());
        try {
            SendResult sendResult = producer.send(msg);
            LOGGER.info("订单[{}]自动收货定时消息提醒发送成功！SendResult = {}", orderId, sendResult);
        } catch (Exception e) {
            LOGGER.error("订单[{}]自动收货定时消息提醒发送失败！", orderId);
            e.printStackTrace();
            throw new IllegalStateException("订单自动收货定时消息发送失败!");
        }
    }

    /**
     * 计算startDeliveryTime：自动收货时间
     *
     * @return startDeliveryTime
     */
    private long calculateAutoReceiptDeliverTime() {
        long postponeTime;
        if (isDebug()) {
            // debug模式下，修改自动收货时间(d->m)
            postponeTime = ordersReceiptLimit * 60 * 1000L;
        } else {
            postponeTime = ordersReceiptLimit * 24 * 60 * 60 * 1000L;
        }
        return System.currentTimeMillis() + postponeTime;
    }

    private boolean isDebug() {
        return Boolean.TRUE.equals(mqRocketDebug);
    }

    @Override
    public ApiResult<NullObject> handleAutoReceiptMsg(String orderId) {
        FieldChecker.checkEmpty(orderId, "订单id");

        GeneticTestingOrder order = orderRepository.findById(orderId);
        if (order == null) {
            LOGGER.error("没有找到订单[{}]信息，无法执行自动收货操作", orderId);
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }

        ClientType clientType = ClientType.getEnum(order.getOrderOrigin());
        if (!clientType.isGeneShop()) {
            LOGGER.error("订单[{}]来源于[{}]，不能执行自动收货操作", orderId, clientType.getIdentifier());
            return ApiResult.fail(OrderErrorCode.ORDER_AUTO_RECEIPT_NOT_GENESHOP);
        }

        OrderStatus currentStatus = OrderStatus.getEnum(order.getStatus());
        if (!OrderStatus.WAIT_RECEIPT_GOODS.equals(currentStatus)) {
            LOGGER.info("订单[{}]当前状态：[{}:{}]，不需要执行自动收货操作", orderId, currentStatus.getCode(), currentStatus.getDesc());
            return ApiResult.succ();
        }
        Date now = new Date();
        order.setStatus(OrderStatus.WAIT_COMMENT.getCode());
        order.setReceiveDateTime(now);
        order.setUpdateDateTime(now);
        orderRepository.updateOrderReceipt(order);
        LOGGER.info("订单[{}]自动收货成功", orderId);

        return ApiResult.succ();
    }

    /**
     * 获取收货人地址
     *
     * @param adressId
     * @return
     * @author FX
     * @date 2018/12/7 13:52
     */
    @Override
    public ApiResult<UserMallAddress> getUserMallAdress(String adressId) {
        UserMallAddress address = orderRepository.getUserMallAdress(adressId);
        address.setFullAddress(address.getFrontAddress() + address.getAddress());
        return ApiResult.succ(address);
    }

    /**
     * 变更套餐
     *
     * @param orderReplacePackageDtos 变更套餐信息
     * @param orderId                 订单id
     * @param userId                  用户id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @Override
    public ApiResult replaceOrderPackage(List<OrderReplacePackageDto> orderReplacePackageDtos, String orderId, String
            userId) {
        //变更前需要判断订单来源，如果订单来源为商城订单，则不能变更套餐
        GeneticTestingOrder order = orderRepository.findById(orderId);
        if (order != null && order.getOrderOrigin() != null) {
            int orderOrigin = order.getOrderOrigin();
            if (ClientType.APP.getCode() == orderOrigin || ClientType.APPLETS.getCode() == orderOrigin || ClientType
                    .PC
                    .getCode() == orderOrigin) {
                return new ApiResult(5001, "failed", "来自商城的订单不能变更套餐", null);
            }
        }
        //判断是否完成了第二次补全（快递公司，快递时间，快递备注，快递单号、快递回单、样本图片等信息）
        //快递回单、样本图片是否为空
        OrderCheckInfoDto result = orderRepository.checkOrderSample(orderId);
        if (result == null || StringUtils.isEmpty(result.getExpressImages()) || StringUtils.isEmpty(result.getSampleImages()) || result.getGoodsConsumes() == null ) {
            LOGGER.error("goods consumes order info is not complete", new IllegalArgumentException());
            return ApiResult.failFormatTip(OrderErrorCode.ORDER_IS_NOT_COMPLETED, "耗材信息");
        }
        //验证快递公司，快递时间，快递备注，快递单号是否为空
        OrderCheckInfoDto checkInfoDto = orderRepository.checkPackageDeliver(orderId);
        List<GeneticTestingExpressDeliveryDto> deliveryDtos = checkInfoDto.getDeliveryDtos();
        if(deliveryDtos==null){
            return ApiResult.failFormatTip(OrderErrorCode.ORDER_IS_NOT_COMPLETED, "物流信息");
        }
        for (GeneticTestingExpressDeliveryDto deliveryDto : deliveryDtos) {
            if (deliveryDto.getExpressCompany() == null || deliveryDto.getRemarks() == null
                    || deliveryDto.getCourierDateTime() == null|| deliveryDto.getExpressNo() == null) {
                LOGGER.error("deliveryDto order info is not complete", new IllegalArgumentException());
                return ApiResult.failFormatTip(OrderErrorCode.ORDER_IS_NOT_COMPLETED, "物流信息");
            }
        }
        //判断选择的新套餐是否有重复的
        boolean b = checkRepeatPackage(orderReplacePackageDtos);
        if(b){
            return new ApiResult(5001, "failed", "不能选择相同的新套餐", null);
        }
        //套餐变更记录编号
        ApiResult<GeneratorDto> changePackageNo = generatorService.numberGenerator(GeneratorEnum.TCBG.getType(), 0, 0);
        //补寄补款编号
        ApiResult<GeneratorDto> replenishmentNoG = generatorService.numberGenerator(GeneratorEnum.BJKX.getType(), 0, 0);
        String replenishmentNo = replenishmentNoG.getData().getSerialNumber();
        //是否需要补款
        Boolean replenishmentFlag = false;
        //补款金额
        BigDecimal replenishmentCount = BigDecimal.ZERO;
        if (orderReplacePackageDtos != null && orderReplacePackageDtos.size() > 0) {
            for (OrderReplacePackageDto orderReplacePackageDto : orderReplacePackageDtos) {
                //查询此套餐的成本
                BigDecimal cost = orderRepository.packageCost(orderReplacePackageDto.getNewPackageId(),
                        orderReplacePackageDto.getNewAgencyId());
                orderReplacePackageDto.setCost(cost);
                //在订单套餐表中新增一条数据
                insertNewOrderPackage(orderReplacePackageDto);
                //在订单套餐变更表插入一条数据
                insertOrderInterchange(orderReplacePackageDto, changePackageNo.getData().getSerialNumber());
                //修改原订单套餐状态以及订单价格
                updateOldInfo(orderReplacePackageDto);
                if (5 == orderReplacePackageDto.getActionType() ||
                        2 == orderReplacePackageDto.getActionType()) {
                    replenishmentFlag = true;
                    replenishmentCount = replenishmentCount.add(orderReplacePackageDto.getSupplementAmount());
                }
                /*
                 * 是否需要生成新的申请单
                 * 如果此订单状态在地管确认以后并且机构为新选择的机构，则需要生成申请单
                 **/
                if (orderReplacePackageDto.getOrderStatus() != null) {
                    if (OrderStatus.WAIT_SAMPLE_CONFIRM.getCode() == orderReplacePackageDto.getOrderStatus() ||
                    OrderStatus.TESTING.getCode() == orderReplacePackageDto.getOrderStatus()) {
                        String requisition = agencyOrderRepository.queryRequisition(orderReplacePackageDto
                        .getNewAgencyId(),
                                orderReplacePackageDto.getOrderId());
                        if (StringUtils.isEmpty(requisition)) {
                            applyOrderService.addApplyOrder(orderReplacePackageDto.getOrderId(), orderReplacePackageDto
                                    .getNewAgencyId());
                        }
                    }
                }
            }
            //如果不需要补款将补款金额置为null
            if (!replenishmentFlag) {
                replenishmentCount = null;
            }
            updateOrderA(orderId, replenishmentFlag, replenishmentNo, replenishmentCount);
        }
        //保存操作记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderId);
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setStatus(order.getStatus());
        orderOperationDetail.setDescription("变更套餐");
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
        return new ApiResult(200, "success", "套餐变更成功", null);
    }

    /***
     * 检查是否选择了相同的套餐
     * @author jcl
     * @date 2019/2/1 16:29
     * @param orderReplacePackageDtos
     * @return
     */
    private boolean checkRepeatPackage(List<OrderReplacePackageDto> orderReplacePackageDtos){
        List<String> newIds = new ArrayList<>();
        orderReplacePackageDtos.forEach(orderReplacePackageDto -> {
            newIds.add(orderReplacePackageDto.getNewPackageId());
        });
        Set newIdSet = new HashSet(newIds);
        //如果有重复的则不行进行变更，并进行提示
        if(newIdSet.size()!=newIds.size()){
            return true;
        }
        return false;
    }

    /***
     * 往订单套餐表插入一条新数据
     * @author jcl
     * @date 2019/1/30 9:41
     * @param orderReplacePackageDto
     * @return
     */
    private void insertNewOrderPackage(OrderReplacePackageDto orderReplacePackageDto) {
        ApiResult<GeneratorDto> generator = generatorService.getGenerator("order_package_replace", null);
        orderReplacePackageDto.setId(generator.getData().getSerialNumber());
        //判断是否需要补款
        if(ActionType.SUPPLEMENT_AMOUNT.getCode().equals(orderReplacePackageDto.getActionType())
                ||ActionType.SUPPLEMENT_SAMPLE_AMOUNT.equals(orderReplacePackageDto.getActionType())){
            orderReplacePackageDto.setIsSupplementFlag(1);
        }else {
            orderReplacePackageDto.setIsSupplementFlag(0);
        }
        //如果新套餐不补寄样本需要把旧套餐的样本信息复制过来
        if (ActionType.NO_AMOUNT.getCode().equals(orderReplacePackageDto.getActionType())
                || ActionType.REFUND_AMOUNT.equals(orderReplacePackageDto.getActionType())
                || ActionType.SUPPLEMENT_AMOUNT.getCode().equals(orderReplacePackageDto.getActionType())) {
            GeneticTestingOrderPackage orderPackage = orderPackageRepository.findOrderPackage(orderReplacePackageDto.getOrderId(), orderReplacePackageDto.getOldPackageId());
            orderReplacePackageDto.setSigner(orderPackage.getSigner());
            orderReplacePackageDto.setSignerDateTime(orderPackage.getSignerDateTime());
            orderReplacePackageDto.setCourierCompanyName(orderPackage.getCourierCompanyName());
            orderReplacePackageDto.setCourierNo(orderPackage.getCourierNo());
            orderReplacePackageDto.setCourierDateTime(orderPackage.getCourierDateTime());
            orderReplacePackageDto.setIsSendWaxBlock(orderPackage.getIsSendWaxBlock());
            orderReplacePackageDto.setCollectSampleDateTime(orderPackage.getCollectSampleDateTime());
            orderReplacePackageDto.setBarCode(orderPackage.getBarCode());
            orderReplacePackageDto.setRemarks(orderPackage.getRemarks());
            orderReplacePackageDto.setCourierRemarks(orderPackage.getCourierRemarks());
            orderReplacePackageDto.setSampleIds(orderPackage.getSampleIds());
            orderReplacePackageDto.setSampleType(orderPackage.getSampleType());
            orderReplacePackageDto.setHospitalCode(orderPackage.getHospitalCode());
            orderReplacePackageDto.setSampleBarcode(orderPackage.getSampleBarcode());
            orderReplacePackageDto.setWhiteCount(orderPackage.getWhiteCount());
            orderReplacePackageDto.setBloodSampleImages(orderPackage.getBloodSampleImages());
        }
        consoleOrderRepository.insertNewOrderPackage(orderReplacePackageDto);
    }

    /***
     * 更新订单A表
     * @author jcl
     * @date 2019/1/23 14:39
     * @param orderId
     * @param replenishmentFlag
     * @param replenishmentNo
     * @param replenishmentCount
     * @return
     */
    private void updateOrderA(String orderId, Boolean replenishmentFlag, String replenishmentNo, BigDecimal replenishmentCount) {
        consoleOrderRepository.updateOrderA(orderId, replenishmentFlag, replenishmentNo, replenishmentCount);
    }

    /***
     * 在订单套餐变更表插入一条数据
     * @author jcl
     * @date 2019/1/4 10:29
     * @param orderReplacePackageDto
     * @return
     */
    public void insertOrderInterchange(OrderReplacePackageDto orderReplacePackageDto, String changePackageNo) {
        //插入新数据之前，将以前此套餐的变更信息删除
        consoleOrderRepository.deleteOldPackageInterchange(orderReplacePackageDto.getOrderId(),
                orderReplacePackageDto.getNewPackageId());
        //新增变更信息
        OrderReplaceInterchangeDto replaceInterchangeDto = new OrderReplaceInterchangeDto();
        ApiResult<GeneratorDto> generator2 = generatorService.getGenerator("genetic_testing_order_interchange", null);
        replaceInterchangeDto.setId(generator2.getData().getSerialNumber());
        replaceInterchangeDto.setOrderId(orderReplacePackageDto.getOrderId());
        replaceInterchangeDto.setRecordNo(changePackageNo);
        replaceInterchangeDto.setDifferenceBalance(orderReplacePackageDto.getSupplementAmount());
        replaceInterchangeDto.setCreateDateTime(new Date());
        replaceInterchangeDto.setDeleteFlag(0);
        if (orderReplacePackageDto.getActionType() != null) {
            //补款
            if (5 == orderReplacePackageDto.getActionType() ||
                    2 == orderReplacePackageDto.getActionType()) {
                replaceInterchangeDto.setReplenishmentFlag(1);
            }
            //不变
            else if (0 == orderReplacePackageDto.getActionType() ||
                    3 == orderReplacePackageDto.getActionType()) {
                replaceInterchangeDto.setReplenishmentFlag(0);
            }
            //退款
            else if (1 == orderReplacePackageDto.getActionType() ||
                    4 == orderReplacePackageDto.getActionType()) {
                replaceInterchangeDto.setReplenishmentFlag(2);
            }
        }
        replaceInterchangeDto.setStatus(0);
        replaceInterchangeDto.setOldPackageId(orderReplacePackageDto.getOldPackageId());
        replaceInterchangeDto.setNewPackageId(orderReplacePackageDto.getNewPackageId());
        replaceInterchangeDto.setActionType(orderReplacePackageDto.getActionType());
        replaceInterchangeDto.setProof(orderReplacePackageDto.getProof());
        replaceInterchangeDto.setReason(orderReplacePackageDto.getReason());
        consoleOrderRepository.insertOrderInterchange(replaceInterchangeDto);
    }

    /***
     * 修改原订单套餐状态以及订单价格
     * @author jcl
     * @date 2019/1/4 10:29
     * @param orderReplacePackageDto
     * @return
     */
    public void updateOldInfo(OrderReplacePackageDto orderReplacePackageDto) {
        BigDecimal orderPrice = orderReplacePackageDto.getOldOrderPrice();
        if (orderReplacePackageDto.getOldOrderPrice() != null && orderReplacePackageDto.getOldPackagePrice() != null
                && orderReplacePackageDto.getNewPackagePrice() != null) {
            orderPrice = orderReplacePackageDto.getOldOrderPrice()
                    .subtract(orderReplacePackageDto.getOldPackagePrice())
                    .add(orderReplacePackageDto.getNewPackagePrice());
        }
        orderReplacePackageDto.setNewOrderPrice(orderPrice);
        //修改原订单总积分
        BigDecimal orderCommission = orderReplacePackageDto.getOldOrderCommission();
        if (orderReplacePackageDto.getOldOrderCommission() != null && orderReplacePackageDto.getOldPackageCommission
                () != null && orderReplacePackageDto.getNewPackageCommission() != null) {
            orderCommission = orderReplacePackageDto.getOldOrderCommission()
                    .subtract(orderReplacePackageDto.getOldPackageCommission())
                    .add(orderReplacePackageDto.getNewPackageCommission());
        }
        orderReplacePackageDto.setNewOrderCommission(orderCommission);
        orderReplacePackageDto.setStatus(OrderPackageStatus.WAIT_CONFIRM.getCode());
        consoleOrderRepository.updateOldInfo(orderReplacePackageDto);
    }

    @Value("${jinll.access_key}")
    private String accessKey;
    @Value("${jinll.secret_key}")
    private String secretKey;
    @Value("${jinll.query_doctor.url}")
    private String queryDoctorUrl;
    @Value("${jinll.query_doctor_no_page.url}")
    private String queryDoctorNoPageUrl;
    @Resource
    private HttpConnectionManager connectionManager;

    /**
     * @param userId   地服id
     * @param name     医生姓名
     * @param phone    医生电话
     * @param pageNo   页数
     * @param pageSize 每页数量
     * @return com.hsgene.common.util.support.PeanutPagination
     * @description 根据地服id，电话，姓名获取医生信息
     * @author maodi
     * @createDate 2019/1/9 14:56
     */
    @Override
    public PeanutPagination queryDoctorByHttp(String userId, String name, String phone, int pageNo, int pageSize) {
        StringBuilder builder = new StringBuilder();
        String andStr = CharactersConstant.AND;
        builder.append("access_key=").append(accessKey).append(andStr).append("timestamp=").append(System
                .currentTimeMillis()).append(andStr).append("auth=1");
        if (StringUtils.isNotBlank(name)) {
            builder.append(andStr).append("name=").append(name);
        }
        builder.append(andStr).append("pageNo=").append(pageNo).append(andStr).append("pageSize=").append(pageSize);
        if (StringUtils.isNotBlank(phone)) {
            builder.append(andStr).append("phone=").append(phone);
        }
        builder.append(andStr).append("userId=").append(userId);
        StringBuilder signBuilder = new StringBuilder();
        signBuilder.append(builder).append(andStr).append("secret_key=").append(secretKey);
        String sign = PayDigestUtil.md5(signBuilder.toString(), CharactersConstant.UTF_8).toUpperCase();
        builder.append(andStr).append("sign=").append(sign);
        String result = connectionManager.doGet(queryDoctorUrl + "?" + builder.toString(), CharactersConstant.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return JSONObject.parseObject(jsonObject.get("data").toString(), PeanutPagination.class);
    }

    /**
     * @param userId 地服id
     * @return com.hsgene.common.util.support.PeanutPagination
     * @description 根据地服id获取医生信息
     * @author maodi
     * @createDate 2019/1/9 16:10
     */
    @Override
    public List<DoctorDto> queryDoctorByHttpNoPage(String userId) {
        StringBuilder builder = new StringBuilder();
        String andStr = CharactersConstant.AND;
        builder.append("access_key=").append(accessKey).append(andStr).append("timestamp=").append(System
                .currentTimeMillis()).append(andStr).append("auth=1").append(andStr).append("userId=").append(userId);
        StringBuilder signBuilder = new StringBuilder();
        signBuilder.append(builder).append(andStr).append("secret_key=").append(secretKey);
        String sign = PayDigestUtil.md5(signBuilder.toString(), CharactersConstant.UTF_8).toUpperCase();
        builder.append(andStr).append("sign=").append(sign);
        String result = connectionManager.doGet(queryDoctorNoPageUrl + "?" + builder.toString(), CharactersConstant
                .UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<DoctorDto> list = new ArrayList<>();
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for (int i = 0, size = jsonArray.size(); i < size; i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            DoctorDto dto = new DoctorDto();
            String id = object.getString("id");
            dto.setIsCertification(object.getInteger("auth"));
            dto.setDept(object.getString("deptName"));
            dto.setId(id);
            dto.setRealName(object.getString("name"));
            dto.setPhone(object.getString("phone"));
            dto.setPost(object.getString("postName"));
            dto.setUserId(id);
            list.add(dto);
        }
        return list;
    }

    /**
     * 平台上传报告
     *
     * @param orderPackageDetails
     * @param userId
     * @return
     * @author FX
     * @date 2019/1/21 15:52
     */
    @Override
    public ApiResult uploadReport(List<OrderPackageDetail> orderPackageDetails, String orderId, String userId) {
        for (OrderPackageDetail c : orderPackageDetails) {
            if (StringUtils.isEmpty(c.getReportUrl())) {
                return ApiResult.fail(OrderErrorCode.TEST_REPORT_CANNOT_BE_EMPTY);
            }
        }
        //判断a表package_change_flag是未确认，不能上传
        GeneticTestingOrderAddtionA addtionAByOrderId = orderRepository.findAddtionAByOrderId(orderId);
        if (addtionAByOrderId.getPackageChangeFlag() != null && addtionAByOrderId.getPackageChangeFlag() == 0) {
            return ApiResult.fail(OrderErrorCode.CHANGE_PACKAGE_NOT_CONFIRMED);
        }
        for (OrderPackageDetail orderPackageDetail : orderPackageDetails) {
            //第一次上传就添加，如果是审核未通过再上传，就更新
            OrderPackageDetail detail = packageDetailMapper.getDetailByOrderIdAndPackageId(orderPackageDetail);
            orderPackageDetail.setReportUploadDateTime(new Date());
            orderPackageDetail.setReportUploadFlag(ReportUploadFlag.getEnum(orderPackageDetail.getReportUploadFlag()).getCode());
            orderPackageDetail.setDeleteFlag(DeleteFlagType.NOT_DELETED.getCode());
            if (detail == null) {
                ApiResult<GeneratorDto> generator = generatorService.getGenerator(null, null);
                if (!generator.isSucc()) {
                    return ApiResult.fail(generator.getError());
                }
                ApiResult<GeneratorDto> generatorDtoApiResult = generatorService.numberGenerator(GeneratorEnum.GTRN.getType(), null, null);
                if (!generatorDtoApiResult.isSucc()) {
                    return ApiResult.fail(generatorDtoApiResult.getError());
                }
                orderPackageDetail.setReportNo(generatorDtoApiResult.getData().getSerialNumber());
                orderPackageDetail.setId(generator.getData().getSerialNumber());
                packageDetailMapper.insertSelective(orderPackageDetail);
            } else {
                orderPackageDetail.setReportNo(detail.getReportNo());
                orderPackageDetail.setId(detail.getId());
                //重新上传，审核未通过原因和状态要置为null
                packageDetailMapper.updateDetailReport(orderPackageDetail);
            }
            //降orderPackage状态改为3-报告待审核
            OrderPackage orderPackage = new OrderPackage();
            orderPackage.setPackageId(orderPackageDetail.getPackageId());
            orderPackage.setGeneticTestingOrderId(orderPackageDetail.getGeneticTestingOrderId());
            orderPackage.setStatus(OrderPackageStatus.REPORT_CHECK.getCode());
            orderPackageMapper.updateByPackageIdAndOrder(orderPackage);
            // 第一次上传检测报告，清除订单套餐超期检测标志
            orderPostponeService.clearPostpone(orderId, orderPackageDetail.getPackageId());

        }
        //保存操作记录-如果是平台上传多个，保存一条记录
        GeneticOrderOperationDetail orderOperationDetail = new GeneticOrderOperationDetail();
        orderOperationDetail.setOrderId(orderId);
        orderOperationDetail.setOperatorId(userId);
        orderOperationDetail.setStatus(OrderStatus.TESTING.getCode());
        orderOperationDetail.setDescription("上传报告");
        orderOperationDetail.setOrderType(1);
        orderService.orderOperationLog(orderOperationDetail);
        return ApiResult.succ();
    }

    @Override
    public ApiResult<NullObject> remarkPostponeOrder(PostponeTestingOrderDto postponeInfo, String operatorId) {
        FieldChecker.checkEmpty(postponeInfo, "超期检测信息");
        FieldChecker.checkEmpty(operatorId, "操作人id");
        postponeInfo.check();

        GeneticTestingOrder order = orderRepository.findById(postponeInfo.getOrderId());
        if (order == null || DeleteFlagType.DELETE.equals(DeleteFlagType.getEnum(order.getDeleteFlag()))) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }
        if (!PostponeFlag.POSTPONE.equals(PostponeFlag.getEnum(order.getPostponeFlag()))) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_POSTPONE);
        }

        order.setPostponeRemarks(postponeInfo.getPostponeRemarks());
        order.setUpdateDateTime(new Date());
        orderRepository.updateOrderForPostpone(order);

        return ApiResult.succ();
    }
}
